import api from '@/api';

const state = {
  // 订单列表
  orderList: [],
  
  // 当前订单类型
  currentType: 'all', // all, pending, paid, completed, cancelled, refund, distribution
  
  // 分页信息
  pagination: {
    page: 1,
    pageSize: 20,
    total: 0,
    hasMore: true
  },
  
  // 订单详情
  orderDetail: null,
  
  // 分销订单列表
  distributionOrders: [],
  
  // 订单统计
  orderStats: {
    pendingCount: 0,      // 待支付
    paidCount: 0,         // 待核销/待发货
    completedCount: 0,     // 已完成
    refundCount: 0,        // 退款单
    totalCount: 0          // 总订单数
  },
  
  // 加载状态
  loading: false
};

const mutations = {
  // 设置订单列表
  SET_ORDER_LIST(state, orders) {
    state.orderList = orders;
  },
  
  // 添加订单到列表
  APPEND_ORDER_LIST(state, orders) {
    state.orderList = [...state.orderList, ...orders];
  },
  
  // 设置当前订单类型
  SET_CURRENT_TYPE(state, type) {
    state.currentType = type;
  },
  
  // 设置分页
  SET_PAGINATION(state, pagination) {
    state.pagination = { ...state.pagination, ...pagination };
  },
  
  // 重置分页
  RESET_PAGINATION(state) {
    state.pagination = {
      page: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    };
  },
  
  // 设置订单详情
  SET_ORDER_DETAIL(state, detail) {
    state.orderDetail = detail;
  },
  
  // 更新订单状态
  UPDATE_ORDER_STATUS(state, { orderId, status }) {
    const index = state.orderList.findIndex(item => item.id === orderId);
    if (index > -1) {
      state.orderList[index].status = status;
    }
    
    if (state.orderDetail && state.orderDetail.id === orderId) {
      state.orderDetail.status = status;
    }
  },
  
  // 设置分销订单列表
  SET_DISTRIBUTION_ORDERS(state, orders) {
    state.distributionOrders = orders;
  },
  
  // 添加分销订单
  ADD_DISTRIBUTION_ORDER(state, order) {
    state.distributionOrders.unshift(order);
  },
  
  // 设置订单统计
  SET_ORDER_STATS(state, stats) {
    state.orderStats = { ...state.orderStats, ...stats };
  },
  
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading;
  },
  
  // 清除订单状态
  CLEAR_ORDER_STATE(state) {
    state.orderList = [];
    state.currentType = 'all';
    state.pagination = {
      page: 1,
      pageSize: 20,
      total: 0,
      hasMore: true
    };
    state.orderDetail = null;
    state.distributionOrders = [];
    state.orderStats = {
      pendingCount: 0,
      paidCount: 0,
      completedCount: 0,
      refundCount: 0,
      totalCount: 0
    };
    state.loading = false;
  }
};

const actions = {
  // 获取订单列表
  async getOrderList({ commit, state }, params = {}) {
    try {
      commit('SET_LOADING', true);
      
      const requestParams = {
        page: state.pagination.page,
        pageSize: state.pagination.pageSize,
        type: state.currentType,
        ...params
      };
      
      const response = await api.order.getList(requestParams);
      const { list, pagination } = response.data;
      
      if (params.append) {
        commit('APPEND_ORDER_LIST', list);
      } else {
        commit('SET_ORDER_LIST', list);
      }
      
      commit('SET_PAGINATION', pagination);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取订单列表失败:', error);
      return { success: false, error: error.message };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  // 设置订单类型
  setOrderType({ commit, dispatch }, type) {
    commit('SET_CURRENT_TYPE', type);
    commit('RESET_PAGINATION');
    return dispatch('getOrderList');
  },
  
  // 加载更多订单
  loadMoreOrders({ commit, state, dispatch }) {
    if (!state.pagination.hasMore || state.loading) {
      return Promise.resolve();
    }
    
    commit('SET_PAGINATION', { page: state.pagination.page + 1 });
    return dispatch('getOrderList', { append: true });
  },
  
  // 获取订单详情
  async getOrderDetail({ commit }, orderId) {
    try {
      commit('SET_LOADING', true);
      const response = await api.order.getDetail(orderId);
      commit('SET_ORDER_DETAIL', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取订单详情失败:', error);
      return { success: false, error: error.message };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  // 创建订单
  async createOrder({ commit }, orderData) {
    try {
      const response = await api.order.create(orderData);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('创建订单失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 支付订单
  async payOrder({ commit }, { orderId, paymentData }) {
    try {
      const response = await api.order.pay(orderId, paymentData);
      commit('UPDATE_ORDER_STATUS', { orderId, status: 'paid' });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('支付订单失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 取消订单
  async cancelOrder({ commit }, orderId) {
    try {
      const response = await api.order.cancel(orderId);
      commit('UPDATE_ORDER_STATUS', { orderId, status: 'cancelled' });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('取消订单失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 确认收货
  async confirmOrder({ commit }, orderId) {
    try {
      const response = await api.order.confirm(orderId);
      commit('UPDATE_ORDER_STATUS', { orderId, status: 'completed' });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('确认收货失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 申请退款
  async applyRefund(_, { orderId, reason, images = [] }) {
    try {
      const response = await api.order.applyRefund(orderId, { reason, images });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('申请退款失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 评价订单
  async rateOrder(_, { orderId, rating, content, images = [] }) {
    try {
      const response = await api.order.rate(orderId, { rating, content, images });
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('评价订单失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 获取分销订单
  async getDistributionOrders({ commit }, params = {}) {
    try {
      commit('SET_LOADING', true);
      const response = await api.order.getDistributionOrders(params);
      commit('SET_DISTRIBUTION_ORDERS', response.data.list);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取分销订单失败:', error);
      return { success: false, error: error.message };
    } finally {
      commit('SET_LOADING', false);
    }
  },
  
  // 获取订单统计
  async getOrderStats({ commit }) {
    try {
      const response = await api.order.getStats();
      commit('SET_ORDER_STATS', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取订单统计失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 删除订单
  async deleteOrder({ commit }, orderId) {
    try {
      const response = await api.order.delete(orderId);
      
      // 从列表中移除
      const index = state.orderList.findIndex(item => item.id === orderId);
      if (index > -1) {
        state.orderList.splice(index, 1);
      }
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('删除订单失败:', error);
      return { success: false, error: error.message };
    }
  }
};

const getters = {
  // 订单列表
  orderList: state => state.orderList,
  
  // 当前订单类型
  currentType: state => state.currentType,
  
  // 分页信息
  pagination: state => state.pagination,
  
  // 订单详情
  orderDetail: state => state.orderDetail,
  
  // 分销订单
  distributionOrders: state => state.distributionOrders,
  
  // 订单统计
  orderStats: state => state.orderStats,
  
  // 加载状态
  loading: state => state.loading,
  
  // 是否有更多数据
  hasMore: state => state.pagination.hasMore,
  
  // 总数
  total: state => state.pagination.total,
  
  // 当前页
  currentPage: state => state.pagination.page,
  
  // 待支付订单数
  pendingCount: state => state.orderStats.pendingCount,
  
  // 待核销订单数
  paidCount: state => state.orderStats.paidCount,
  
  // 已完成订单数
  completedCount: state => state.orderStats.completedCount,
  
  // 退款订单数
  refundCount: state => state.orderStats.refundCount
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};